<?php
namespace app\client\controller;

class Agent extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function agetRule() {
        $userId = request()->get('storeId', 0, 'intval');
        
        $where['user_id'] = !empty($userId) ? $userId : $this->userid;
        //['fee', 'slogan', 'min_number', 'sale_service', 'remarks']
        $rule = model('AgentRule')->findOne($where);
        return successResult($rule);
    }
    
    public function apply() {
        $params = request()->post();
        
        
        $storeId = isset($params['storeId']) ? intval($params['storeId']) : 0;
        if($storeId <= 0) {
            return errorResult();
        }
        
        $rule = model('AgentRule')->findOne(['user_id' => $storeId], ['fee']);
        if(empty($rule)) {
            return errorResult();
        }
        
        $userId = $this->userid;
        
        $orderNo = getOrderNo($userId);
        
        $data = ['order_no' => $orderNo, 'amount' => $rule['fee'], 'user_id' => $userId, 'merchant_id' => $storeId, 'create_time' => time()];
        
        $model = model('ApplyAgentOrder');
        
        $model->startTrans();
        
        try {
            $rs = $model->add($data);
            if(!$rs) {
                $model->rollback();
                return errorResult();
            }
            
            //发起支付
            $wxPay = new \app\client\wxpay\WxPayUnifiedOrder(session('user')['openid']);
            $wxPay->setOrder([
                'body' => '测试的支付',
                'order_no' => $orderNo,
                'amount' => $rule['fee'],
                'notify_url' => 'agentApplyNotify'
            ]);
            
            $payParams = $wxPay->getParams(); //获取发起支付的参数
            
            if($payParams['err']){
                $model->rollback();
                return errorResult('abc');
            }
            
            $model->commit();
            
            return successResult(['wxparam' => $payParams['params']]);
            
        } catch (\Exception $e) {
            $model->rollback();
            return errorResult();
        }
    }
    
    public function setAgentRule() {
        $params = request()->post();
        $params['picture'] = isset($params['picture']) ? $params['picture'] : [];
        if(!is_array($params['picture'])){
            return errorResult();
        }
        $model = model('AgentRule');
        $rule = $model->findOne(['user_id' => $this->userid], ['id']);
        if(empty($rule)) {
            $params['user_id'] = $this->userid;
            $rs = $model->add($params);
            if(!$rs) {
                return errorResult();
            }
        }else {
            $rs = $model->modify(['id' => $rule['id']], $params);
            if(!$rs) {
                return errorResult();
            }
        }
        
        
        return successResult();
    }
}